package me.zhengjie.modules.device.service.impl;

import me.zhengjie.modules.device.domain.EnvironmentalDevice;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.device.repository.EnvironmentalDeviceRepository;
import me.zhengjie.modules.device.service.EnvironmentalDeviceService;
import me.zhengjie.modules.device.service.dto.EnvironmentalDeviceDTO;
import me.zhengjie.modules.device.service.mapper.EnvironmentalDeviceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;

/**
* @author 张鹏
* @date 2019-05-08
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class EnvironmentalDeviceServiceImpl implements EnvironmentalDeviceService {

    @Autowired
    private EnvironmentalDeviceRepository environmentalDeviceRepository;

    @Autowired
    private EnvironmentalDeviceMapper environmentalDeviceMapper;

    @Override
    public EnvironmentalDeviceDTO findById(Long id) {
        Optional<EnvironmentalDevice> environmentalDevice = environmentalDeviceRepository.findById(id);
        ValidationUtil.isNull(environmentalDevice,"EnvironmentalDevice","id",id);
        return environmentalDeviceMapper.toDto(environmentalDevice.get());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public EnvironmentalDeviceDTO create(EnvironmentalDevice resources) {
        return environmentalDeviceMapper.toDto(environmentalDeviceRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(EnvironmentalDevice resources) {
        Optional<EnvironmentalDevice> optionalEnvironmentalDevice = environmentalDeviceRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalEnvironmentalDevice,"EnvironmentalDevice","id",resources.getId());

        EnvironmentalDevice environmentalDevice = optionalEnvironmentalDevice.get();
        // 此处需自己修改
        resources.setId(environmentalDevice.getId());
        environmentalDeviceRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        environmentalDeviceRepository.deleteById(id);
    }
}